package com.xie.server;

import com.alibaba.fastjson.JSONObject;
import com.xie.pojo.SysMessage;
import com.xie.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@ServerEndpoint("/web/{uid}")
@Component
public class WebSocketServer {
    @Autowired
    public static MessageService messageService;

    private static int onLineUser=0;

    private Session session;

    private Map<Integer,WebSocketServer> clients=new HashMap<>();

    private Integer uid;

    @OnOpen
    public void onOpen(@PathParam("username") Integer uid, Session session){
        this.session=session;
        this.uid=uid;
        clients.put(uid,this);
        addOnlineCount();
        System.out.println(uid+"连接!当前人数"+getOnlineCount());
        try {
            if (uid!=1){
                List<SysMessage> sysMessages = messageService.pullMessageByUserId(this.uid);
                Map<String,Object> jsonMessage=new HashMap<>();
                jsonMessage.put("messageType",1);
                jsonMessage.put("rows",sysMessages);
                sendMessageTo(JSONObject.toJSONString(jsonMessage),uid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @OnClose
    public void onClose(){
        clients.remove(uid); //从set中删除
        subOnlineCount();
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(message);
            String textMessage = jsonObject.getString("message");
            String fromusername = jsonObject.getString("username");
            String tousername = jsonObject.getString("to");
            //messageType 1代表上线 2代表下线 3代表在线名单  4代表普通消息
            Map<String,Object> map1 = new HashMap<>();
            map1.put("textMessage",textMessage);
            map1.put("fromusername",fromusername);
            if(tousername.equals("All")){
                map1.put("messageType",6);
                SysMessage sms=new SysMessage();
                sms.setMessage(textMessage);
                sms.setType(1);
                //messageService.addTzAll(tz);
                map1.put("tousername","所有人");
                sendMessageAll(JSONObject.toJSONString(map1));
            }
            else{
                map1.put("messageType",4);
                map1.put("tousername",tousername);
                sendMessageTo(JSONObject.toJSONString(map1),uid);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }


    public static synchronized int getOnlineCount() {
        return onLineUser;
    }

    public static synchronized void addOnlineCount() {
        onLineUser++;
    }

    public static synchronized void subOnlineCount() {
        onLineUser--;
    }

    public void sendMessageTo(String message, Integer ToUserId) throws IOException {
        for (WebSocketServer item : clients.values()) {
            if (item.uid == ToUserId ) {
                item.session.getBasicRemote().sendText(message);
                break;
            }
        }
    }

    public void sendMessageAll(String message) throws IOException {
        for (WebSocketServer item : clients.values()) {
            if (item.uid!=1){
                item.session.getBasicRemote().sendText(message);
            }
        }
    }
}
